package microgame.toolset.datatable;

import Core.Log4j2;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Hashtable;

public class DataTableManager {
    private Hashtable<String, DataTable> tableMap = new Hashtable<>();

    private static DataTableManager instance;

    private String basePath;

    public static DataTableManager Instance() {
        if (instance == null) {
            instance = new DataTableManager();
        }
        return instance;
    }

    public void Init() throws  Exception {
        String startDir = System.getProperty("user.dir");
        Load(startDir + "/Config/DataTable.cfg");
    }

    public void Load(String path) throws Exception {
        basePath = System.getProperty("user.dir") + "/Config/";

        BufferedReader br = new BufferedReader(new FileReader(path));

        try {
            StringBuilder sb = new StringBuilder();
            // first line is all properties' key
            String firstRow = br.readLine();
            String secondRow = br.readLine();

            String line = br.readLine();
            while (line != null && line != "\r\n" && line != "\n") {
                ProcessLine(line);
                line = br.readLine();
            }
        } finally {
            br.close();
        }
    }

    public DataTable GetDataTable(String key) {
        return tableMap.get(key);
    }

    private void ProcessLine(String line) throws Exception {
        String[] columns = line.split("\t");
        if (columns.length != 2) {
            throw new Exception("Not a valid DataTable.cfg.");
        }

        String tablePath = basePath + columns[1];
        DataTable dt = new DataTable();
        dt.LoadDataFile(tablePath);

        tableMap.put(columns[0], dt);
    }
}
